package myJs.projectCps.enrichBarPlot

import com.softwaremill.quicklens._
import myJs.Utils.layer
import myJs.api.Api
import myJs.cps._
import myJs.myPkg.Swal.swal
import myJs.myPkg._
import myJs.myPkg.reactHookForm.{FormProvider, ReactHookForm, UseFormOptions, yupResolver}
import myJs.myPkg.tabs._
import myJs.projectCps._
import myJs.tool.Tool
import myJs.tool.Tool._
import org.scalajs.macrotaskexecutor.MacrotaskExecutor.Implicits._
import shared.pojo.mission._
import shared.tool.DefaultPickle
import upickle.default._

import scala.scalajs.js
import scala.scalajs.js.{Date, JSON}

import japgolly.scalajs.react.vdom.all._
import japgolly.scalajs.react._
import japgolly.scalajs.react.React.Fragment
import japgolly.scalajs.react.util.EffectCatsEffect._
import myJs.myPkg.Hooks._
import cats.effect._
import myJs.Implicits._

/** Created by yz on 3/11/2020
  */
object Cp {

  case class Props(idStr: String = ""){
    @inline def render: VdomElement = {
      Component(this)
    }
  }

  val plotO = EnrichBarPlot

  val Component = ScalaFnComponent[Props] { props =>
    val (imageUrl, setImageUrl) = useState("")
    val initTab = List("layout", "color", "font")(0)
    val (tab, setTab) = useState(initTab)
    val useForm = ReactHookForm.useForm(UseFormOptions(mode = "onChange", resolver = yupResolver(Schema.schema)))
    val (basicData, setBasicData) = useState(plotO.Request())

    object FTool {

      def tabChange = (v: String) => {
        setTab(v)
      }

      def vChange[T](f: PathLazyModify[plotO.Request, T]) = (g: T => T) => {
        setBasicData {
          f.using(g)
        }
      }

      def formSubmit = useForm.myHandleSubmit((data: js.Dictionary[js.Any]) => {
        println(JSON.stringify(data))
        FTool.myRun
      })

      def refreshImage ={
        val url =
          s"${Api.missionTool.workspaceImage(Tool.getMissionId, s"${plotO.pngFileNamePrefix(props.idStr)}.png")}&time=${new Date()}"
        setImageUrl(url)
      }

      def myRun = {
        val index = layer.alert(Tool.myElement, Tool.layerOptions)
        val request = basicData.modify(_.id).setTo(Tool.getMissionId.toInt).modify(_.idStr).setTo(props.idStr)
        Api.missionTool.myPlot(DefaultPickle.write(request)).flatMapSync { response =>
          layer.close(index)
          if (response.valid) {
            FTool.refreshImage
          } else SyncIO{
            layer.close(index)
            swal(SwalOptions(title = "Error", text = response.message, `type` = "error"))
          }
        }
      }

      def refreshBasicData = {
        val request = PlotConfigDataRequest(
          id = Tool.getMissionId.toInt,
          fileName = s"${plotO.configFileName}",
          idStr = props.idStr
        )
        Api.missionTool.plotConfigData(request).flatMapSync { str =>
          val response = read[plotO.Request](str)
          setBasicData(response)
        }
      }

    }

    useEffect(
     {
        FTool.refreshImage.to[IO] >>
        FTool.refreshBasicData
      },
      List(props.idStr)
    )

    Fragment(
      div(
        className := "col-sm-8",
        id := "content",
        ImageToolCp.Props(
          pdfUrl =
            Api.missionTool.downloadWorkspaceFile(Tool.getMissionId, s"${plotO.pngFileNamePrefix(props.idStr)}.pdf"),
          pngUrl =
            Api.missionTool.downloadWorkspaceFile(Tool.getMissionId, s"${plotO.pngFileNamePrefix(props.idStr)}.png")
        ).render,
        img(src := s"${imageUrl}", width := "100%")
      ),
      div(
        className := "col-sm-4",
        id := "sidebar",
        FormProvider(
          control = useForm.control,
          formState = useForm.formState,
          setValue = useForm.setValue _,
          trigger = useForm.trigger _
        )(
          form(
            onSubmit := FTool.formSubmit,
            className := "form-horizontal",
            Tabs(id = "tab", activeKey = tab, onSelect = FTool.tabChange, transition = false)(
              Tab(eventKey = "layout", title = s"${messages("layout")}")(
                div(
                  marginTop := "20px",
                  LayoutCp.Props(
                    basicData = basicData.layout,
                    basicDataChange = FTool.vChange(modifyLens[plotO.Request](_.layout))
                  ).render
                )
              ),
              Tab(eventKey = "color", title = s"${messages("colors")}")(
                div(
                  marginTop := "20px",
                  ColorCp.Props(
                    basicData = basicData.color,
                    basicDataChange = FTool.vChange(modifyLens[plotO.Request](_.color))
                  ).render
                )
              ),
              Tab(eventKey = "font", title = s"${messages("fontArg")}")(
                div(
                  marginTop := "20px",
                  FontCp.Props(
                    basicData = basicData.font,
                    basicDataChange = FTool.vChange(modifyLens[plotO.Request](_.font))
                  ).render
                )
              )
            ),
            div(
              className := "form-group",
              div(
                className := "actions col-sm-offset-2 col-sm-4",
                button(
                 width := "90%",
                  `type` := "submit",
                  className := "btn btn-primary",
                  s" ${messages("run")}"
                )
              )
            ),
            div(
              className := "row",
              marginLeft := 0.px,
              div(
                className := "col-sm-12",
                p(
                  color := "#232327",
                  messages("reRunInfo")
                )
              )
            )
          )
        )
      )
    )

  }

}
